<template>
  <div class="page page_scroll">
    <!-- 顶部 开始 -->
    <div class="top_info">

      <!-- 常用功能 开始 -->
      <div class="cell">
        <div class="title"><span>常用功能</span></div>
        <div class="a_list">
          <div class="a_box" v-for="(item,index) in linkList" :key="index" @click="linkUrlEvent(item)">
            <div class="icon">
              <img :src="item.icon" alt="" />
            </div>
            <div class="name">{{item.name}}</div>
          </div>
        </div>
      </div>
      <!-- 常用功能 end -->

      <!-- 业绩排行 开始 -->
      <div class="cell">
        <div class="title">
          <span>业绩排行</span>
          <div class="filter">
            <span class="sp_name">查询日期：</span>
            <el-date-picker v-model="resultDate" class="a_picker" size="mini" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd">
            </el-date-picker>
            <el-button type="primary" size="mini" @click="getList">查询</el-button>
          </div>
        </div>
        <div class="div_tab">
          <el-table class="el_table" :data="resultList" max-height="200" size="small" v-loading="loading" element-loading-text="加载中...">
            <el-table-column label="排名">
              <template slot-scope="scope">
                <img :src="iconList[scope.$index+1]" class="img" alt="" v-if="scope.$index<5">
                <span class="index_tag" v-else>{{scope.$index+1}}</span>
              </template>
            </el-table-column>
            <el-table-column label="姓名" prop="employeeName"></el-table-column>
            <!-- <el-table-column label="新客户数" prop="newCount"></el-table-column> -->
            <el-table-column label="转化率" prop="contractRate"></el-table-column>
            <el-table-column label="收款金额" prop="incomeAmount"></el-table-column>
          </el-table>
        </div>
      </div>
      <!-- 业绩排行 end -->

    </div>
    <!-- 顶部 end -->

    <!-- 客户状态统计 开始 -->
    <div class="row_box">
      <div class="row_left">
        <div class="head">
          <!-- <span class="name">客户状态统计</span> -->
          <div class="name">
            <span>客户状态统计</span>
            <span class="small">(管理员显示全部，店长显示本店数据，组长显示组内数据)</span>
          </div>
          <div class="filter_box">
            <span class="sp_name">查询日期：</span>
            <el-date-picker v-model="clueForm.time" class="a_picker" size="mini" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" @change="e => onChange(e,'clueForm')">
            </el-date-picker>
            <span class="sp_name">渠道：</span>
            <el-select size="mini" v-model="clueForm.channeId" filterable class="a_select" clearable>
              <el-option v-for="(item,index) in channelList" :key="index" :label="item.nickname" :value="item.id"></el-option>
            </el-select>
            <span class="sp_name">媒体：</span>
            <el-select size="mini" v-model="clueForm.media" filterable class="a_select" clearable>
              <el-option v-for="(item,index) in mediaList" :key="index" :label="item" :value="item"></el-option>
            </el-select>
            <el-button type="primary" size="mini" class="s_btn" @click="getCustomerState">查询</el-button>
          </div>
        </div>

        <!-- 图表区域 开始 -->
        <div class="chart_box" v-loading="bloading" element-loading-text="加载中...">
          <div class="chart" id="singleClueChart"></div>
        </div>
        <!-- 图表区域 end -->

      </div>
    </div>
    <!-- 客户状态统计 开始 -->

    <!-- 客户标签统计 开始 -->
    <div class="row_box">
      <div class="row_left">
        <div class="head">
          <!-- <span class="name">客户标签统计</span> -->
          <div class="name">
            <span>客户标签统计</span>
            <span class="small">(管理员显示全部，店长显示本店数据，组长显示组内数据)</span>
          </div>
          <div class="filter_box">
            <span class="sp_name">查询日期：</span>
            <el-date-picker v-model="tagForm.time" class="a_picker" size="mini" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" @change="e => onChange(e,'tagForm')">
            </el-date-picker>
            <span class="sp_name">渠道：</span>
            <el-select size="mini" v-model="tagForm.channeId" filterable class="a_select" clearable>
              <el-option v-for="(item,index) in channelList" :key="index" :label="item.nickname" :value="item.id"></el-option>
            </el-select>
            <span class="sp_name">媒体：</span>
            <el-select size="mini" v-model="tagForm.media" filterable class="a_select" clearable>
              <el-option v-for="(item,index) in mediaList" :key="index" :label="item" :value="item"></el-option>
            </el-select>
            <el-button type="primary" size="mini" class="s_btn" @click="getLabelStatic">查询</el-button>
          </div>
        </div>

        <!-- 图表区域 开始 -->
        <div class="chart_box" v-loading="cloading" element-loading-text="加载中...">
          <div class="chart" id="tagStaticChart"></div>
        </div>
        <!-- 图表区域 end -->

      </div>
    </div>
    <!-- 客户标签统计 开始 -->

  </div>
</template>

<script>
import { broadcast, deepClone, showToast } from "@/utils/util";
import moment from "moment";
import GlsxDialog from "@/components/Dialog/index";
import {
  GET_INDEX_INCOMESORT,
  GET_CUSTOMER_STATE,
  GET_CUSTOMER_LABEL,
} from "@/http/sale";
import { GET_ALL_CHANNEL, GET_ALL_MEDIA } from "@/http/public";
import * as echarts from "echarts";
import { ECHARTCOLOR } from "@/common/constants";
export default {
  name: "Dashboard",
  components: {
    GlsxDialog,
  },
  data() {
    return {
      linkList: [
        {
          icon: require("@/assets/images/link_01.png"),
          name: "创建客户",
          url: "addClient",
        },
        {
          icon: require("@/assets/images/link_11.png"),
          name: "新客户",
          url: "NewClients",
        },
        {
          icon: require("@/assets/images/link_03.png"),
          name: "进件回款",
          url: "MyInput",
        },
        {
          icon: require("@/assets/images/link_04.png"),
          name: "我的签约",
          url: "MyContract",
        },
        {
          icon: require("@/assets/images/link_05.png"),
          name: "签约",
          url: "addContract",
        },
        // {
        //   icon: require("@/assets/images/link_06.png"),
        //   name: "电子签约",
        //   url: "addContract",
        //   option: { type: 1 },
        // },
      ],
      resultList: [],
      updateTime: "",
      orderType: 2,
      iconList: {
        1: require("@/assets/images/icon_one.png"),
        2: require("@/assets/images/icon_two.png"),
        3: require("@/assets/images/icon_three.png"),
        4: require("@/assets/images/icon_four.png"),
        5: require("@/assets/images/icon_five.png"),
      },
      clueForm: {},
      channelList: [],
      mediaList: [],
      tagForm: {},
      chartColor: ECHARTCOLOR,
      resultDate: [],
      loading: false,
      bloading: false,
      cloading: false,
    };
  },
  mounted() {
    let start = moment().startOf("month").format("YYYY-MM-DD");
    let end = moment().endOf("month").format("YYYY-MM-DD");
    this.resultDate = [start, end];

    this.$set(this.clueForm, "time", [start, end]);
    this.$set(this.tagForm, "time", [start, end]);

    this.getList();
    this.getChannel();
    this.getMedia();
    this.getCustomerState();
    this.getLabelStatic();
  },
  methods: {
    // 获取业绩排行榜
    getList() {
      let oParams = {};
      let m = this.resultDate;
      oParams.startDate = m ? m[0] : "";
      oParams.endDate = m ? m[1] : "";
      this.loading = true;
      GET_INDEX_INCOMESORT(oParams).then((res) => {
        this.loading = false;
        this.resultList = res.data || [];
      });
    },

    // 新增客户
    addCustomer() {
      broadcast("customer.add");
    },

    // 新增预约
    addBook() {
      broadcast("customer.add.book");
    },

    // 收款变动
    addCollect() {
      broadcast("customer.collect.add", { status: 4, title: "收款变动" });
    },

    // 页面跳转
    linkUrlEvent(row) {
      if (row.url == "addContract") {
        this.addContract();
        return false;
      }
      if (row.url) {
        this.$router.push({ name: row.url, query: row.option });
      }
    },

    // 新增签约
    addContract() {
      broadcast("look.user.sign", {});
    },

    // 数字单位处理
    showNumber(str) {
      let o = Number(str || 0);
      console.log(str);
      return Math.round(o / 10000);
    },

    // 处理月份展示
    showRateTime(str) {
      if (!str) {
        return "";
      }
      let m = moment(str).format("M");
      return m;
    },

    // 获取客户状态统计
    getCustomerState() {
      let _this = this;
      let oParams = this.getParams();
      this.bloading = true;
      GET_CUSTOMER_STATE(oParams).then((res) => {
        this.bloading = false;
        let list = res.data || [];
        let xAxis = [];
        let yAxis = [];
        let o = {};
        list.map((k) => {
          xAxis.push(k.processName);
          yAxis.push(k.counts);
        });
        o.series = [{ name: "", data: yAxis }];
        o.xaxis = xAxis;
        o.barWidth = 50;
        let options = _this.initChartData(o, "bar", list);
        _this.initDealChart(options, "singleClueChart");
      });
    },

    // 获取所有渠道
    getChannel() {
      GET_ALL_CHANNEL().then((res) => {
        this.channelList = res.data || [];
      });
    },

    // 获取所有媒体
    getMedia() {
      GET_ALL_MEDIA().then((res) => {
        this.mediaList = res.data || [];
      });
    },

    // 获取查询参数
    getParams(id) {
      let oid = id || "clueForm";
      let oParams = deepClone(this[oid]);
      let n = oParams.time;
      if (n && n.length >= 0) {
        oParams.startDate = n[0];
        oParams.endDate = n[1];
      }
      delete oParams.time;
      return oParams;
    },

    // 生成图表
    initChart(id, options) {
      var chartDom = document.getElementById(id);
      var myChart = echarts.init(chartDom);
      myChart.setOption(options);
    },

    // 生成折线图、柱状图图表
    initDealChart(oParams, id) {
      let option = {
        tooltip: {
          trigger: "axis",
          formatter: oParams.formatter || "",
        },
        legend: {
          right: "16px",
          data: oParams.legend,
        },
        grid: {
          left: "16",
          right: "26",
          bottom: "16",
          containLabel: true,
        },
        xAxis: [
          {
            type: "category",
            //boundaryGap: oParams.boundaryGap,
            data: oParams.xaxis,
          },
        ],
        yAxis: [
          {
            type: "value",
          },
        ],
        color: this.chartColor,
        series: oParams.series,
      };
      //this.initChart("dealChart", option);
      this.initChart(id, option);
    },

    // 处理折线图数据
    initChartData(obj, type, list) {
      if (!obj) {
        return "";
      }
      let options = {};
      let _names = [];
      let _arr = [];
      obj.series.map((k) => {
        let m = [];
        let o = {
          type: type || "line",
          smooth: true,
          areaStyle: {},
          emphasis: {
            focus: "series",
          },
          barWidth: obj.barWidth,
        };
        k.data.map((j) => {
          j = j ? Number(j.toFixed(0)) : j;
          m.push(j);
        });
        o.name = k.name;
        o.data = m;
        o.itemStyle = {
          normal: {
            label: {
              show: true,
              position: "top",
              formatter: function (params) {
                let co = list[params.dataIndex];
                let s = co ? co.rate : "";
                return s;
              },
            },
          },
        };

        _arr.push(o);
        _names.push(k.name);
      });

      options.legend = _names;
      options.series = _arr;
      options.xaxis = obj.xaxis;
      return options;
    },

    // 获取label
    getLabelStatic() {
      let _this = this;
      let oParams = _this.getParams("tagForm");
      this.cloading = true;
      GET_CUSTOMER_LABEL(oParams).then((res) => {
        this.cloading = false;
        let list = res.data || [];
        let xAxis = [];
        let yAxis = [];
        let o = {};
        list.map((k) => {
          xAxis.push(k.label);
          yAxis.push(k.count);
        });
        o.series = [{ name: "", data: yAxis }];
        o.xaxis = xAxis;
        o.barWidth = 50;
        let options = _this.initChartData(o, "bar", list);
        _this.initDealChart(options, "tagStaticChart");
      });
    },

    // 监听变化
    onChange(e, id) {
      if (!e) {
        this.$set(this[id], "time", []);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/assets/styles/index.scss";
.page {
  background: #f2f2f2;
  padding: 20px 10px;
}
.target_box {
  .a_input {
    width: 80%;
  }
}
</style>
